//
//  ViewController.m
//  FMRecordVideo
//
//  Created by qianjn on 2017/2/27.
//  Copyright © 2017年 SF. All rights reserved.
//
//  Github:https://github.com/suifengqjn
//  blog:http://gcblog.github.io/
//  简书:http://www.jianshu.com/u/527ecf8c8753
#import "ViewController.h"
#import "FMFileVideoController.h"
#import "FMWriteVideoController.h"
#import "HXPhotoView.h"
#import "HXCustomNavigationController.h"
#import <CoreServices/CoreServices.h>
#import "UploadImagesViewController.h"
#import "UploadNaviViewController.h"
#import "VoiceRecordViewControlller.h"
#import "VoiceRecord2ViewControlller.h"
@interface ViewController () <HXCustomNavigationControllerDelegate , FMFileVideoControllerDelegate, VoiceRecord2ViewControlllerDelegate>
{
    NSMutableArray *_images;
}

@property (strong, nonatomic) HXPhotoManager *manager;
@property (weak, nonatomic) IBOutlet UITextField *ticket;


@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}


- (IBAction)UIImagePicker:(id)sender {
    
//    FMImagePicker *picker = [[FMImagePicker alloc] init];
//    [self presentViewController:picker animated:YES completion:nil];
//
}

- (HXPhotoManager *)manager {
    if (!_manager) {
        _manager = [[HXPhotoManager alloc] initWithType:HXPhotoManagerSelectedTypePhotoAndVideo];
        _manager.configuration.openCamera = NO;
        _manager.configuration.lookLivePhoto = YES;
        _manager.configuration.photoMaxNum = 9;
        _manager.configuration.videoMaxNum = 1;
        _manager.configuration.maxNum = 9;
        _manager.configuration.themeColor = kRGB(84, 182, 54);
        //        _manager.configuration.languageType = HXPhotoLanguageTypeKo;
        _manager.configuration.videoMaximumSelectDuration = 600;
        _manager.configuration.videoMinimumSelectDuration = 0;
        _manager.configuration.videoMaximumDuration = 60.f;
        _manager.configuration.maxVideoClippingTime = 60.f;
        _manager.configuration.creationDateSort = NO;
        _manager.configuration.saveSystemAblum = YES;
        _manager.configuration.showOriginalBytes = YES;
//                _manager.configuration.reverseDate = YES;
        //        _manager.configuration.showDateSectionHeader = YES;
        _manager.configuration.selectTogether = NO;
        _manager.configuration.rowCount = 4;
        //        _manager.configuration.movableCropBox = YES;
        //        _manager.configuration.movableCropBoxEditSize = YES;
        //        _manager.configuration.movableCropBoxCustomRatio = CGPointMake(1, 1);
        //        _manager.configuration.requestImageAfterFinishingSelection = YES;
        //        _manager.configuration.replaceCameraViewController = YES;
                _manager.configuration.albumShowMode = HXPhotoAlbumShowModeDefault;
        
//        HXWeakSelf
//        _manager.configuration.shouldUseCamera = ^(UIViewController *viewController, HXPhotoConfigurationCameraType cameraType, HXPhotoManager *manager) {
//
//            // 这里拿使用系统相机做例子
//            UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
//            imagePickerController.delegate = (id)weakSelf;
//            imagePickerController.allowsEditing = NO;
//            NSString *requiredMediaTypeImage = ( NSString *)kUTTypeImage;
//            NSString *requiredMediaTypeMovie = ( NSString *)kUTTypeMovie;
//            NSArray *arrMediaTypes;
//            if (cameraType == HXPhotoConfigurationCameraTypePhoto) {
//                arrMediaTypes=[NSArray arrayWithObjects:requiredMediaTypeImage,nil];
//            }else if (cameraType == HXPhotoConfigurationCameraTypeVideo) {
//                arrMediaTypes=[NSArray arrayWithObjects:requiredMediaTypeMovie,nil];
//            }else {
//                arrMediaTypes=[NSArray arrayWithObjects:requiredMediaTypeImage, requiredMediaTypeMovie,nil];
//            }
//            [imagePickerController setMediaTypes:arrMediaTypes];
//            // 设置录制视频的质量
//            [imagePickerController setVideoQuality:UIImagePickerControllerQualityTypeHigh];
//            //设置最长摄像时间
//            [imagePickerController setVideoMaximumDuration:60.f];
//            imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
//            imagePickerController.navigationController.navigationBar.tintColor = [UIColor whiteColor];
//            imagePickerController.modalPresentationStyle=UIModalPresentationOverCurrentContext;
//            [viewController presentViewController:imagePickerController animated:YES completion:nil];
//        };
    }
    return _manager;
}


- (IBAction)record:(id)sender
{
    VoiceRecord2ViewControlller *controller = [[VoiceRecord2ViewControlller alloc] init];
    controller.delegate = self;
    controller.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    [self presentViewController:controller animated:YES completion:nil];
}

#pragma mark -- 声音上传
- (void)VoiceRecord2ViewControlllerDismissWithUrl:(NSURL *)url
{
    dispatch_async(dispatch_get_main_queue(), ^{
        UploadImagesViewController *vc = [[UploadImagesViewController alloc] initWithMp3Url:url type:UploadTypeMp3];
        vc.ticket = self.ticket.text;
        vc.orgId = @"2553715";
        UploadNaviViewController *navi = [[UploadNaviViewController alloc] initWithRootViewController:vc];
        [self presentViewController:navi animated:YES completion:nil];
    });
}


#pragma mark -- 拍摄
- (IBAction)fileOut:(id)sender {
    
    FMFileVideoController *fileVC = [[FMFileVideoController alloc] init];
    fileVC.delegate = self;
    UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:fileVC];
    [self presentViewController:navi animated:YES completion:nil];
    
}

#pragma mark -- FMFileVideoControllerDelegate

- (void)FMFileVideoControllerImage:(UIImage *)image
{
    UploadImagesViewController *vc = [[UploadImagesViewController alloc] initWithImages:@[image] type:UploadTypeImages];
    vc.ticket = self.ticket.text;
    vc.orgId = @"2553715";
    UploadNaviViewController *navi = [[UploadNaviViewController alloc] initWithRootViewController:vc];
    [self presentViewController:navi animated:YES completion:nil];
}

- (void)FMFileVideoControllerVideoUrl:(NSURL *)url
{
    UploadImagesViewController *vc = [[UploadImagesViewController alloc] initWithAvSetUrl:url type:UploadTypeVideo];
    vc.ticket = self.ticket.text;
    vc.orgId = @"2553715";
    UploadNaviViewController *navi = [[UploadNaviViewController alloc] initWithRootViewController:vc];
    [self presentViewController:navi animated:YES completion:nil];
}


- (IBAction)selectMedia:(id)sender
{
    HXCustomNavigationController *nav = [[HXCustomNavigationController alloc] initWithManager:self.manager delegate:self];
    [self presentViewController:nav animated:YES completion:nil];
}

/**
 点击完成按钮
 
 @param photoNavigationViewController self
 @param allList 已选的所有列表(包含照片、视频)
 @param photoList 已选的照片列表
 @param videoList 已选的视频列表
 @param original 是否原图
 */
- (void)photoNavigationViewController:(HXCustomNavigationController *)photoNavigationViewController
                       didDoneAllList:(NSArray<HXPhotoModel *> *)allList
                               photos:(NSArray<HXPhotoModel *> *)photoList
                               videos:(NSArray<HXPhotoModel *> *)videoList
                             original:(BOOL)original;
{
    if (photoList.count) {
        _images = [NSMutableArray array];
        for (NSInteger i = 0; i < photoList.count; i ++) {
            HXPhotoModel *model = photoList[i];
            UIImage *previewPhoto = model.previewPhoto;
            PHAsset *asset = model.asset;
            
            if (!asset && previewPhoto) {
                [_images addObject:previewPhoto];
                
                if (_images.count == photoList.count) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        UploadImagesViewController *vc = [[UploadImagesViewController alloc] initWithImages:_images type:UploadTypeImages];
                        vc.ticket = self.ticket.text;
                        vc.orgId = @"2553715";
                        UploadNaviViewController *navi = [[UploadNaviViewController alloc] initWithRootViewController:vc];
                        [self presentViewController:navi animated:YES completion:nil];
                    });
                }
                
                break;
            }
            
            PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
            options.version = PHVideoRequestOptionsVersionOriginal;
            
            [[PHImageManager defaultManager] requestImageDataForAsset:asset options:options resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
                UIImage *image = [UIImage imageWithData:imageData];
                
                image = [self fixOrientation:image];
                NSLog(@"%@", image);
                [_images addObject:image];
                
                if (_images.count == photoList.count) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        UploadImagesViewController *vc = [[UploadImagesViewController alloc] initWithImages:_images type:UploadTypeImages];
                        vc.ticket = self.ticket.text;
                        vc.orgId = @"2553715";
                        UploadNaviViewController *navi = [[UploadNaviViewController alloc] initWithRootViewController:vc];
                        navi.navigationBar.barStyle = UIBarStyleDefault;
                        [self presentViewController:navi animated:YES completion:nil];
                    });
                }
            }];
        }
    }else if (videoList.count) {
        HXPhotoModel *model = videoList[0];
        PHAsset *asset = model.asset;
        if (asset == nil) {
            NSURL *url = model.videoURL;
            if (url) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    UploadImagesViewController *vc = [[UploadImagesViewController alloc] initWithAvSetUrl:url type:UploadTypeVideo];
                    vc.ticket = self.ticket.text;
                    vc.orgId = @"2553715";
                    UploadNaviViewController *navi = [[UploadNaviViewController alloc] initWithRootViewController:vc];
                    navi.navigationBar.barStyle = UIBarStyleDefault;
                    [self presentViewController:navi animated:YES completion:nil];
                });
            }
            
            return;
        }
        
        [[PHImageManager defaultManager] requestAVAssetForVideo:asset options:nil resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
            
            AVURLAsset *urlSet = (AVURLAsset *)asset;
            NSURL *url = urlSet.URL;
            
            if (url) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    UploadImagesViewController *vc = [[UploadImagesViewController alloc] initWithAvSetUrl:url type:UploadTypeVideo];
                    vc.ticket = self.ticket.text;
                    vc.orgId = @"2553715";
                    UploadNaviViewController *navi = [[UploadNaviViewController alloc] initWithRootViewController:vc];
                    [self presentViewController:navi animated:YES completion:nil];
                });
            }
        }];
    }
}

- (void)photoNavigationViewController:(HXCustomNavigationController *)photoViewController didEditVideo:(HXPhotoModel *)model
{
    PHAsset *asset = model.asset;
    if (asset == nil) {
        NSURL *url = model.videoURL;
        if (url) {
            dispatch_async(dispatch_get_main_queue(), ^{
                UploadImagesViewController *vc = [[UploadImagesViewController alloc] initWithAvSetUrl:url type:UploadTypeVideo];
                vc.ticket = self.ticket.text;
                vc.orgId = @"2553715";
                UploadNaviViewController *navi = [[UploadNaviViewController alloc] initWithRootViewController:vc];
                navi.navigationBar.barStyle = UIBarStyleDefault;
                [self presentViewController:navi animated:YES completion:nil];
            });
        }
        
        return;
    }
    
    [[PHImageManager defaultManager] requestAVAssetForVideo:asset options:nil resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
        
        AVURLAsset *urlSet = (AVURLAsset *)asset;
        NSURL *url = urlSet.URL;
        
        if (url) {
            dispatch_async(dispatch_get_main_queue(), ^{
                UploadImagesViewController *vc = [[UploadImagesViewController alloc] initWithAvSetUrl:url type:UploadTypeVideo];
                vc.ticket = self.ticket.text;
                vc.orgId = @"2553715";
                UploadNaviViewController *navi = [[UploadNaviViewController alloc] initWithRootViewController:vc];
                [self presentViewController:navi animated:YES completion:nil];
            });
        }
    }];
}

/**
 点击取消
 
 @param photoNavigationViewController self
 */
- (void)photoNavigationViewControllerDidCancel:(HXCustomNavigationController *)photoNavigationViewController;
{
    
}


- (IBAction)writer:(id)sender {
    
    FMWriteVideoController *writeVC = [[FMWriteVideoController alloc] init];
    UINavigationController *NAV = [[UINavigationController alloc] initWithRootViewController:writeVC];
    [self presentViewController:NAV animated:YES completion:nil];
    
}

/** 解决旋转90度问题 */
- (UIImage *)fixOrientation:(UIImage *)aImage
{
    //    NSData *data1 = UIImagePNGRepresentation(aImage);
    //    NSData *data11 = UIImageJPEGRepresentation(aImage, 0.6);
    // No-op if the orientation is already correct
    if (aImage.imageOrientation == UIImageOrientationUp)
        return aImage;
    
    
    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    
    //    NSData *data2 = UIImagePNGRepresentation(img);
    
    return img;
}


@end
